<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <!-- <el-form-item label="备件">
          <eamPartsInput
            style="width: 100%"
            :key="'2'"
            :isMultiple="false"
            :showSelectDevice="materialListTwo"
            :maxCollapseTags="2"
            @get-device="(id, object) => getDeviceTwo(id, object)"
          />
        </el-form-item>
        <el-form-item label="使用部门" style="width: 250px">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids)"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('使用部门')"
            :selectData="searchParam.usingDepartmentId"
          />
        </el-form-item>
        <el-form-item label="备件类型">
          <el-select
            style="width: 100%"
            v-model="searchParam.spareType"
            placeholder="请选择备件类型"
            clearable
          >
            <el-option
              v-for="item in useDictionary('SpareType')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备种类">
          <el-tree-select
            clearable
            @keyup.enter="search"
            :placeholder="`请选择${'设备'}类型`"
            v-model="searchParam.equipTypeId"
            :data="catalogList"
            node-key="id"
            :props="{
              label: 'assetTypeName',
              value: 'id',
              children: 'nodes',
            }"
            :render-after-expand="false"
            :check-strictly="true"
          />
        </el-form-item> -->
        <!-- <el-form-item label="工单状态">
          <el-select
          
            v-model="searchParam.repairStatus"
            placeholder="请选择工单状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('EamRepairStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="统计日期" style="width: 350px">
          <el-date-picker
            v-model="searchParam.reportQueryTimeSearch"
            type="datetimerange"
            range-separator="至"
            :shortcuts="globalShortcuts"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getrepairTime"
          />
        </el-form-item> -->

        <el-form-item label="生产线">
          <el-input
            v-model="searchParam.assetCode"
            placeholder="请输入生产线"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item class="w-[100px]">
          <el-select
            v-model="searchParam.year"
            placeholder="请选择"
            filterable
            :suffixIcon="() => '年'"
          >
            <el-option
              v-for="item in yearOptions"
              :key="item"
              :value="item"
              :label="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="restHandle">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!-- <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          @click="
            useDownload(
              '/andon/andcall/callInformExport',
              '故障报修工单',
              searchParam
            )
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template> -->

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @sort-change="onTableSortChanged"
        @selection-change="handleSelectionChange"
        :header-cell-style="{ textAlign: 'center' }"
      >
        <el-table-column
          :label="`设备:${dataList[0].assetCode}`"
          min-width="200"
          show-overflow-tooltip
        >
          <el-table-column
            :label="`月份:${dataList[0].month}`"
            min-width="200"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column
          label=""
          prop="assetName"
          min-width="120"
          show-overflow-tooltip
        >
          <el-table-column
            label="代号"
            prop="number"
            min-width="120"
            show-overflow-tooltip
          />
        </el-table-column>
        <el-table-column
          label=""
          prop="assetName"
          min-width="120"
          show-overflow-tooltip
        >
          <el-table-column
            label="合计"
            prop="tatol"
            min-width="120"
            show-overflow-tooltip
          />
        </el-table-column>
        <el-table-column
          label="造型线"
          prop="assetName"
          min-width="120"
          show-overflow-tooltip
        >
          <el-table-column
            v-for="(item, index) in 12"
            :label="item"
            prop="assetName"
            min-width="120"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ scope.row[item] }}
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <eam-repair-order-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :assetKind="assetKind"
      @reset-table="(id:string) => (id?.length ? getTableList() : search())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import { globalShortcuts } from "@/utils/dateUtils";
import request from "@/utils/request";
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "EAMEQUDEVICEMANGEREPORTPARTSSTATISTICS",
  inheritAttrs: false,
});

const assetKind = 1;
// 请求参数
const requestApi = "/eam/eamrepairorder/queryUsageStatistics";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  spareCode: "",
  usingDepartmentId: "",
  usingDepartmentName: "",
  spareType: "",
  equipTypeId: "",
  reportQueryTimeSearch: [],
  reportQueryStartTime: "",
  reportQueryEndTime: "",
};

const deleteParam = {
  api: "/eam/eamrepairorder/delete",
  data: { assetKind },
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const restHandle = () => {
  materialListTwo.value = [];
  reset();
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

onMounted(() => {
  getTableList();
  getLocationInfoTree();
});
// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamrepairorder/get/${id}`,
    method: "get",
    data: {
      assetKind,
    },
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开维修单表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改维修单";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增维修单";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开维修单表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "维修单详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getrepairTime(data: any) {
  if (data) {
    searchParam.value.reportQueryStartTime = data[0];
    searchParam.value.reportQueryEndTime = data[1];
  } else {
    searchParam.value.reportQueryStartTime = "";
    searchParam.value.reportQueryEndTime = "";
  }
}

function getSelectIds(ids: [] | string) {
  if (ids) {
    searchParam.value.usingDepartmentId = ids;
  } else {
    searchParam.value.usingDepartmentId = "";
  }
}
// 使用部门选择
const dataObject = (item: string) => {
  return {
    name: item,
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};
const materialListTwo = ref([]);

// 获取选中的数据进行回显并赋值
function getDeviceTwo(Ids: string[], Objects: any) {
  if (Ids.length > 0) {
    searchParam.value.spareCode = Objects[0].spareCode;
    // searchParam.value.materialId = Objects[0].materialName;
    // searchParam.value.materialId = Objects[0].materialCode;
    //   materialListTwo.value = Objects;
  } else {
    searchParam.value.spareCode = "";
    //   searchParam.value.materialId = "";
    //   searchParam.value.materialId = "";
    //   // formData.dstCode = Objects[0].binCode;
    //   // formData.dstId = Objects[0].id;
    //   materialListTwo.value = [];
  }
}

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/eamCommon/getAvailableTree",
    method: "POST",
    data: { assetKind: 1 },
  }).then((res) => {
    catalogList.value = res.data;
  });
};

// 获取年度列表
const yearOptions = ref();
async function getYears() {
  const { data } = await request({
    url: "/system/dateInfo/getYearList",
    method: "post",
    data: {},
  });
  yearOptions.value = data;
}

const dataList = [
  {
    month: "一月",
    assetCode: "111",
    title: "班次时间（分钟）",
    number: "A",
    tatol: "222",
    1: "111",
    2: "111",
    3: "111",
    4: "111",
  },
];

onMounted(() => {
  getCAtalogList();
  getYears();
});
</script>
<style lang="scss" scoped>
:deep(.search-container) {
  .el-select .el-input .el-select__caret.el-icon {
    font-style: normal;
    transform: none !important;
  }
}
</style>
